var pathname = window.location.pathname;
var hashValue = window.location.hash;
var commentsLimit = 25;
var commentsOffset = 0;
var commentsVisible = 0;

$(document).ready(function() {
    $('#storyText').disableTextSelect();
    $(document).bind('keydown keypress mouseup',function(e) {
        var sel = rangy.getSelection();
        if(sel.containsNode(document.getElementById('storyText'),false) || sel.containsNode(document.getElementById('storyText'),true)) {
            sel.removeAllRanges();
        }
        return true;
    });

	var endlessScrollOptions = {
		bottomPixels: ($(document).height()-$('.panel').height())-500,
		fireOnce: true,
		fireDelay: 250,
		loader: '',
		insertAfter: '#show_comments',
		callback: function() {
			fetchComments();
		}
	};

	$(document).keydown(function(objEvent) {
		if (objEvent.ctrlKey) {
			if (objEvent.keyCode==65 || objEvent.keyCode==67) {
				return false;
			}
		}
	});

	if ($('#comment').length>0 && !isMobile()) {
		$('#comment').elastic();
	}

	if (commentsTotal>0 && hashValue.indexOf('comment')===-1 && pathname.indexOf('comment')===-1) {
		if ($.browser.msie && $.browser.version<9) {
			$(window).endlessScroll(endlessScrollOptions);
		}
		else {
			$(document).endlessScroll(endlessScrollOptions);
		}
	}

	if (pathname.indexOf('comment')!==-1) {
		if ($('#show_comments').children().length>0) {
			$('html, body').animate({ scrollTop: $("#comments").offset().top });
		}
		else {
			$('html, body').animate({ scrollTop: $("#comments").offset().top });
			fetchComments();
		}
	}

	if (hashValue=="#comments") {
		fetchComments();
	}

	if ($('#youtubeid').val()!='') {
		$('#youtube_span').show();
	}

	if ($('#photos').val()!='') {
		$('#photos_span').show();
	}

	$('#youtubeid').live('keyup focus blur', function() {
		if ($('#youtubeid').val()!='') {
			$('#youtube_span').show();
		}
		else {
			$('#youtube_span').hide();
		}
	});

	$('#photos').live('keyup focus blur', function() {
		if ($('#photos').val()!='') {
			$('#photos_span').show();
		}
		else {
			$('#photos_span').hide();
		}
	});

	$('#youtube_span').click(function() {
		$('#youtubeid').val('').focus();
		updateYoutube($('#youTube_textid').val(), '');
		$('#youtube_span').hide();
	});

	$('#photos_span').click(function() {
		$('#photos').val('').focus();
		updateSlideShow($('#photos_textid').val(), '');
		$('#photos_span').hide();
	});

	$('#show_more_comments').click(function() {
		if ($("#msgDeleted").length>0) {
			$("#msgDeleted").css("display", "none");
		}
		ga_track('Story Comments', 'Show More', 'Current Comment Count', commentsVisible);
		fetchComments();
	});

	$('#submit_comment').click(function() {
		var comment = $.trim($('#comment').val());
		if (comment=="") {
			$('#commentlog').html("Write your comment");
			return;
		}
		if (comment.length>2000) {
			$('#commentlog').html("Your comment exceeds 2000 characters");
			return;
		}
		if (typeof($('#fbupdate'))!='undefined' && $('#fbupdate').prop('checked')) {
			facebook_prompt_permission('publish_stream', function() {
				submitComment();
			});
			return;
		}

		$('#commentlog').html("");
		submitComment();
	});

	$('.deletecomment').live('click', function() {
		var commentButton = $(this);
		var commentElement = commentButton.parent().parent();

		// Extracting comment id
		var commentID = commentButton.attr('id');
		commentID = commentID.substring(commentID.indexOf('-')+1, commentID.length);

		if (confirm(deleteConfirm)) {		// deleteConfirm is declared in associated php file
			deleteComment(commentID, commentElement);
		}
	});

	$('.unflagcomment').live('click', function() {
		var commentButton = $(this);
		var commentElement = $(this).parent().parent();

		// Extracting comment id
		var commentID = commentButton.attr('id');
		commentID = commentID.substring(commentID.indexOf('-')+1, commentID.length);

		unflagComment(commentID, commentElement);
	});

	$('#main_toolbar td:not(#writer_tools_edit)').click(function() {
		var container = $('#'+$(this).attr('id')+'_container');
		$('#writer_tools td').removeClass('pushed');
		if (container.is(':visible')) {
			$('#writer_tools .sub_toolbar, #promote_email_success, #promote_email_fail').hide();
			$('#writer_tools').animate({ height: $('#main_toolbar').outerHeight(true)+'px' });
		}
		else {
			$(this).addClass('pushed');
			$('#writer_tools .sub_toolbar').hide();
			$('#writer_tools').animate({ height: (container.outerHeight(true)+$('#main_toolbar').outerHeight(true))+'px' }, function() {
				container.show();
			});
		}
		return false;
	});

	$('#promote_email').click(function() {
		$(this).addClass('pushed');
		var newHeight = ($('#writer_tools_promote_container').outerHeight(true)+$('#main_toolbar').outerHeight(true))+$('#promote_email_entry').outerHeight(true);
		if (!$('#promote_email_entry').is(':visible')) {
			$('#writer_tools').animate({ height: newHeight+'px' }, function() {
				$('#promote_email_entry').show();
				cloudsponge.launch();
			});
		}
		else {
			cloudsponge.launch();
		}
	});

	$('#promote_email_entry input').click(function() {
		if ($.trim($('#contact_list').val())=='') {
			alert('Please enter some email addresses or click the E-mail button to import them from your address book.');
			return false;
		}
		//email check
		var regEx = /^[!#$%&\'*+-/=?^_`{|}~a-z0-9-]+(\.[!#$%&\'*+-/=?^_`{|}~a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
    var emailString = $('#contact_list').val();
    emailString = emailString.replace(/\s/g, ""); //remove whitespace
    var emailInput = ($.trim(emailString).split(','));
    var newEmailString = "";

    //now only keep chars in between < >, as well as checking email validity
    for (i = 0; i<emailInput.length; i++) {
      var temp = emailInput[i];
      temp = temp.slice(temp.indexOf("<")+1, temp.lastIndexOf(">"));

      if(temp.length > 0){
        emailInput[i] = temp;
      }

      if(newEmailString.length == 0){
        newEmailString += emailInput[i];
      }
      else{
        newEmailString += "," + emailInput[i];
      }

      if (!(emailInput[i]).match(regEx)) {
        alert('Invalid email list submitted');
        return false;
      }
    }

		$('#promote_email_entry .spinner').show();
		$.ajax({
				   type: 'POST',
				   url: '/apiv2/story_invites?id='+storyID+'&emails='+newEmailString,
				   success: function(data, status) {
					   ga_track('Story Sharing', 'emails sent');
					   $('#promote_email_entry .spinner').hide();
					   $('#promote_email_success').show('slow');
					   $('#contact_list').val('');
				   },
				   error: function(data, status) {
					   $('#promote_email_entry .spinner').hide();
					   $('#promote_email_fail').show();
				   }
			   });

		return false;
	});

	$('#addVideoForm').submit(function() {
		updateYoutube(this.textid.value, this.youtube.value);
		$('#youtube_span').show();
		return false;
	});

	$('#addSlideshowForm').submit(function() {
		updateSlideShow(this.textid.value, this.photos.value)
		$('#photos_span').show();
		return false;
	});

	$('#votebox').click(function() {
		$('#votemore').fadeIn();
		return false;
	});

	$('#dedication_viewed img, #dedication_viewed a').tipsy({ gravity: 'w' });
	$('#try_it_button').tipsy({gravity:'ne', html:true, delayIn:200});

	$('#remove_dedication td').click(function() {
		if (confirm('Are you sure you want to remove this dedication?')) {
			$.ajax({
					   type: 'POST',
					   url: '/apiv2/dedicate?id='+storyID+'&type=remove',
					   success: function(data, status) {
						   $('#dedication').css('visibility', 'hidden');
						   $('#remove_dedication').hide();
						   $('#writer_tools').animate({ height: ($('#writer_tools').outerHeight(true)+15)+'px' }, function() {
							   $('#dedicate_buttons').show();
						   });
					   },
					   error: function(data, status) {
					   }
				   });
		}
		return false;
	});

	$('#dedicate_buttons').live('click', function(e) {
		var target = $(e.target);
		switch (target.parent('td').attr('id') || target.attr('id')) {
			case 'dedicate_fb':
				facebook_prompt_permission('', function() {
					$.facebox({ ajax: '/dialog/dedicate?type=facebook&story_id='+storyID+'&facebook_access_token='+FBStatus.accessToken });
				});
				break;
			case 'dedicate_wattpad':
				$.facebox({ ajax: '/dialog/dedicate?type=wattpad&story_id='+storyID });
				break;
			case 'dedicate_outsider':
				$.facebox({ ajax: '/dialog/dedicate?type=outsider&story_id='+storyID });
				break;
		}
		return false;
	});

	$('#dedication_remind').click(function() {
		$.ajax({
				   type: 'POST',
				   url: '/apiv2/dedicate?id='+storyID+'&type=remind',
				   success: function(data, status) {
					   $('#dedication_remind').tipsy('hide');
					   $('#dedication_remind').remove();
				   }
			   });
	});

	$('.paging_form').submit(function() {
		updatePage(parseInt($(this).find('input:text').val()));
		return false;
	});

	$('.story_meta.comments').click(function() {
		goTo('comments');
	});

	handlePaging(page);
	if (location.hash!='') {
		hashChange();
	}

	$(window).bind('hashchange', function () {
		hashChange();
	});

	// float panels
    var actionPanelTop;
    var recsPanelTop;
    $(window).scroll(function (event) {
        var topOffset = 55;
        var topOverlap = 10;
		var y = $(this).scrollTop();
        if (!$('#float_action_bar').hasClass('panel_fixed') && $('#float_action_bar').offset().top < y + topOffset - topOverlap) {
            actionPanelTop = $('#float_action_bar').offset().top;
            $('#float_action_bar').addClass('panel_fixed');
        }
        else if ($('#float_action_bar').hasClass('panel_fixed') && $('#float_action_bar').offset().top < actionPanelTop) {
            $('#float_action_bar').removeClass('panel_fixed');
        }

		if ($('#float_recs').is(":visible")) {
            if (!$('#float_recs').hasClass('panel_fixed') && $('#float_recs').offset().top < y + topOffset + $('#float_action_bar').outerHeight()) {
                recsPanelTop = $('#float_recs').offset().top;
                $('#float_recs').addClass('panel_fixed');
            }
            else if ($('#float_recs').hasClass('panel_fixed') && $('#float_recs').offset().top < recsPanelTop) {
                $('#float_recs').removeClass('panel_fixed');
            }
		}
	});
});

function goToTop() {
	$('html, body').animate({scrollTop:0}, 200);
}

function handlePaging(page) {
	if (page<1) {
		page = 1;
	}
	if (totalPages>1) {
		if (page==1) {
			$('.hide_when_last_page').show();
			$('.prev_page').css("visibility", 'hidden');
			$('.next_page').css("visibility", 'visible');
		}
		else if (page==totalPages) {
			$('.hide_when_last_page').hide();
			$('.next_page').css("visibility", 'hidden');
			$('.prev_page').css("visibility", 'visible');
		}
		else {
			$('.hide_when_last_page').show();
			$('.next_page, .prev_page').css("visibility", 'visible');
		}
	}

	if (page==totalPages) {
		$('#nextChapter').show();
	}
	else {
		$('#nextChapter').hide();
	}

	if (page==1) {
		$('#fullLink').show();
		$('#dedication').show();
	}
	else {
		$('#fullLink').hide();
		$('#dedication').hide();
	}
}

function loadpage(story_id, page_number) {
  goToTop();
  ga_track('Stories', 'Go to Page', pageUrl);
  $('#page_spinner').css("visibility", "visible");
  if (!$.browser.msie || $.browser.version>=9) {
    $('#storyText').css('opacity', '0.4');
  }
  var oldStoryText = $('#storyText').html();
  $.ajax({
    type:'GET',
    url:API2_PATH+'storytext',
    data:{ id:story_id, page:page_number},
    success:function (data) {
      $('#storyText').html(data);
      $('.paging_input').val(page_number);
      handlePaging(page_number);
      if (!$.browser.msie || $.browser.version>=9) {
        $('#storyText').css('opacity', '1');
      }
      $('#page_spinner').css("visibility", "hidden");
      document.title = document.title.replace(/( - \w+ )[0-9]+( - Wattpad$)/, "$1"+page_number+"$2");
    },
    error:function (data, status) {
      $('#page_spinner').css("visibility", "hidden");
      $('#storyText').html(oldStoryText);
      if (!$.browser.msie || $.browser.version>=9) {
       $('#storyText').css('opacity', '1');
      }
    }
  });
}

function hashChange() {
	var hash = location.hash.substr(2);
	updatePage(parseInt(hash.substr(hash.indexOf('p=')).split('&')[0].split('=')[1]));
}

function updatePage(pageNum) {
	if (!isNaN(pageNum) && pageNum>0 && pageNum<=totalPages && page!=pageNum) {
		page = pageNum;
		loadpage(storyID, page);
		location.hash = '!p='+(page);
	}
}

function nextPageClick() {
	updatePage(page+1);
}

function prevPageClick() {
	updatePage(page-1);
}

function updateYoutube(storyId, youTubeId) {
    $.ajax({
        url: API2_PATH+'textaddvideophotos',
        type: 'POST',
        data: { id: storyID, youtube: youTubeId },
        success:	function(data) {
            youTubeId = data.youtube;
            $('#youtubeContainer').html('');
            if (youTubeId!='') {
                $('<embed></embed>', {
                    src: 'http://www.youtube.com/v/'+youTubeId+'&hl=en_US&fs=1&rel=0',
                    type: 'application/x-shockwave-flash',
                    width: '300',
                    height: '240',
                    allowscriptaccess: true,
                    allowfullscreen: true,
                    wmode: 'opaque'
                }).appendTo('#youtubeContainer');
							$('#youtubeContainer').parent().show();
							$('#youtubeContainer').slideDown();
							$('html, body').animate({ scrollTop: $("#youtubeContainer").parent().offset().top-$('#float_action_bar').outerHeight() }, 1000);
            }
        },
        error: function(data) {
            alert((JSON.parse(data.responseText)['message']));
        }
    });
}

function updateSlideShow(storyId, photosURL) {
    $.ajax({
        url: API2_PATH+'textaddvideophotos',
        type: 'POST',
        data: { id: storyId, photos: photosURL },
        success: function(data) {
            photosURL = data.photos;
            $('#photosContainer').html('');
            if (photosURL!='') {
                var photoElement = getPhotoElement(photosURL);
								$('#photosContainer').parent().show();
								$('#photosContainer').append(photoElement);
								$('#photosContainer').slideDown();
								$('html, body').animate({ scrollTop: $("#photosContainer").parent().offset().top-$('#float_action_bar').outerHeight() }, 1000);
            }
        },
        error: function(data) {
            alert((JSON.parse(data.responseText)['message']));
        }
    });
}

function getPhotoElement(url) {
	if (url.match(/pbw$/)) {
		var embed = document.createElement('embed');
		embed.src = 'http://w879.photobucket.com/pbwidget.swf?pbwurl='+url;
		embed.type = 'application/x-shockwave-flash';
		embed.height = '240';
		embed.width = '300';
		$(embed).attr('wmode', 'transparent');
		return embed;
	}
	else {
		var img = document.createElement('img');
		img.src = url;
		img.width = 300;
		img.height = 240;
		return img;
	}
}

function showFull(group_parts, group_partnum) {
	$('#fullLink').hide();
	$.get(API2_PATH+'storytext', {id: storyID}, function (data) {
		$('#storyText').html(data);
		$('#pagingButtons').hide();
		if (group_parts>group_partnum) {
			$('#nextChapter').show();
		}
	}, 'json');
}

function updateCharCount() {
	var charCountElement = $('#charcount');
	var charCount = parseInt(charCountElement.html());
	var commentCharCount = $.trim($('#comment').val()).length;

	if (charCount!=commentCharCount) {
		charCountElement.html(commentCharCount);

		if (commentCharCount>2000) {
			charCountElement.css('color', 'red');
		}
		else {
			charCountElement.css('color', '');
		}
	}
}

function replyComment(str) {
	$('#comment').focus();
	$('#comment').val($('#comment').val()+str);
	updateCharCount();
}

function fetchComments() {
	$('#show_more_comments_spinner').css('visibility', 'visible');
	$('#show_more_comments').css('visibility', 'hidden');
	$.ajax({
        type: 'GET',
        url: API2_PATH+'comments',
        data: {id: storyID, offset: commentsOffset, limit: commentsLimit, generate_html: true},
        success: function(data) {
            var total = data['total'];
            var comments = data['items'];

            for (var i = 0; i<comments.length; ++i) {
                var comment = $(comments[i]['html']).hide();
                comment.appendTo('#show_comments').slideDown();
            }

            commentsOffset += comments.length;
            commentsVisible += comments.length;

            if (commentsTotal!=total) {
                commentsTotal = total;
                updateCommentCount();
            }

            $('#show_more_comments_spinner').css('visibility', 'hidden');
            if ((commentsTotal-commentsVisible)<=0) {
                $('#no_more_comments').css('visibility', 'visible');
            }
            else {
                $('#show_more_comments').css('visibility', 'visible');
            }
        },
        error: function(data) {
            $('#show_more_comments').css('visibility', 'visible');
            $('#show_more_comments_spinner').css('visibility', 'hidden');
            $('#commentlog').html(JSON.parse(data.responseText)['message']);
        }
    });
}

function submitComment() {
	$('#submit_comment_spinner').css('visibility', 'visible');
	$('#comment').attr('disabled', 'true');
	var fbupdate = 0,twitterupdate = 0,tumblrupdate = 0;
	if (window['update_to_fb']) {
		fbupdate = 1;
	}
	if (window['update_to_twitter']) {
		twitterupdate = 1;
	}
	if (window['update_to_tumblr']) {
		tumblrupdate = 1;
	}
	$.ajax({
        type: 'POST',
        url: API2_PATH+'comments',
        data: {
            id: storyID,
            req_type: 'new',
            comment: $.trim($('#comment').val()),
            generate_html: true,
            fbupdate: fbupdate,
            twitterupdate: twitterupdate,
            tumblrupdate: tumblrupdate
        },
        success: function(data) {
            $('#submit_comment_spinner').css('visibility', 'hidden');
            if (data.html!='') {
                commentsOffset += 1;
                commentsVisible += 1;
                commentsTotal += 1;

                // Display comment
                var comment = $(data.html).hide();
                comment.prependTo('#show_comments').slideDown('slow', function() {
                    // Update comment textarea
                    $('#comment').val('').removeAttr('disabled').trigger('change');
                    updateCharCount();
                });

                // Update comment count
                updateCommentCount();
            }
            else {
                $('#commentlog').html('Error displaying comment. Please refresh your page.');
            }
        },
        error: function(data) {
            $('#submit_comment_spinner').css('visibility', 'hidden');
            $('#comment').removeAttr('disabled');
            $('#commentlog').html(JSON.parse(data.responseText)['message']);
        }
    });
}

function deleteComment(commentID, commentElement) {
	$.ajax({
        type: 'POST',
        url: API2_PATH+'comments',
        data: {
            id: storyID,
            req_type: 'delete',
            commentid: commentID
        },
        success: function() {
            commentsOffset -= 1;
            commentsVisible -= 1;
            commentsTotal -= 1;

            // Display comment
            commentElement.slideUp('slow', function() {
                $(this).remove();
            });

            // Update comment count
            updateCommentCount();
        },
        error: function(data) {
            $('#commentlog').html(JSON.parse(data.responseText)['message']);
            $(window).scrollTop($('#commentlog').position().top);
        }
    });
}

function unflagComment(commentID, commentElement) {
	$.ajax({
        type: 'POST',
        url: API2_PATH+'comments',
        data: {
            id: storyID,
            req_type: 'unflag',
            commentid: commentID,
            generate_html: true
        },
        success: function(data) {
            // Replacing current comment element with new HTML
            commentElement.replaceWith(data.html);
        },
        error: function(data) {
            $('#commentlog').html(JSON.parse(data.responseText)['message']);
            $(window).scrollTop($('#commentlog').position().top);
        }
    });
}

function updateCommentCount() {
	$('.commentbox span').html(String(commentsTotal));
	$('#commentcount').html('('+commentsTotal+')');
}
